<template>
  <div>
    <!-- 头部 -->
    <a-form
      ref="searchRef"
      :model="searchForm"
      :hideRequiredMark="true"
      style="margin-bottom: 20px"
    >
      <a-row>
        <a-button
          type="primary"
          @click="add"
          v-has="{ a: $route, b: 2 }"
          class="d-a-center"
          >新增</a-button
        >
        <a-col :span="4" :offset="8">
          <a-form-item name="saleValue" label="位置">
            <a-select
              ref="select"
              v-model:value="searchForm.pictureType"
              @focus="focus"
              @change="handleChange"
              placeholder="请选择"
            >
              <a-select-option
                v-for="item in swiperTypes"
                :value="item.id"
                :key="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="4" :offset="1">
          <a-form-item name="saleValue" label="标题">
            <a-input
              placeholder="根据标题模糊搜索"
              v-model:value="searchForm.keyWord"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="2" :offset="1">
          <a-button type="primary" @click="search" class="d-a-center"
            >搜索</a-button
          >
        </a-col>
        <a-col :span="2">
          <a-button @click="handleReset" class="d-a-center">重置</a-button>
        </a-col>
      </a-row>
    </a-form>
    <!-- 父表格 -->

    <div class="fl">
      <a-table
        :columns="serviceColums"
        :data-source="serviceList"
        style="width: 200px"
        :pagination="false"
      >
        <template #service="{ record, index }">
          <div class="service">
            <div
              class="name"
              :class="index == serviceAct ? 'name-act' : ''"
              @click="getChildrenList(record, index)"
            >
              {{ record.name }}
            </div>
          </div>
        </template>
      </a-table>
      <!-- 列表 -->
      <a-table
        style="flex: 1"
        :columns="columns"
        :data-source="list"
        bordered
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ y: 540, x: 'auto' }"
      >
        <template #pictureUrl="{ record }">
          <img
            style="width: 100px; height: 40px"
            :src="record.pictureUrl"
            alt=""
          />
        </template>
        
        <template #pictureType="{ record }">
          <div>{{ record.pictureType == 1 ? "首页" : "订单页" }}</div>
        </template>
        <template #operation="{ record }">
          <a-button
            type="link"
            @click="edit(record, '编辑')"
            v-has="{ a: $route, b: 2 }"
            >编辑</a-button
          >
          <a-button
            type="link"
            @click="edit(record, '查看')"
            v-has="{ a: $route, b: 1 }"
            >查看</a-button
          >
          <a-button
            type="link"
            danger
            @click="del(record.key)"
            v-has="{ a: $route, b: 2 }"
            >删除</a-button
          >
        </template>
      </a-table>
    </div>
    <!-- 多项删除 -->
    <!-- <a-button type="danger" @click="listDel">删除</a-button> -->

    <div>
      <!-- 弹窗 -->
      <a-modal
        v-if="visible"
        :visible="visible"
        :title="modalTitle"
        width="50%"
        :maskClosable="false"
        @cancel="closeModal('visible')"
      >
        <!--  -->
        <!-- okText="保存" -->
        <!-- @ok="addSwiper" -->
        <!--  -->
        <template v-slot:footer>
          <div class="d-j-around">
            <a-button @click="closeModal('visible')" class="d-a-center"
              >关闭</a-button
            >
            <a-button
              v-if="modalTitle != '查看'"
              type="primary"
              @click="addSwiper"
              class="d-a-center"
              >保存</a-button
            >
          </div>
        </template>
        <a-form :model="form" :rules="rules" :labelCol="labelCol" ref="formRef">
          <a-form-item label="标题" name="pictureName">
            <a-input
              placeholder="请输入标题"
              v-model:value="form.pictureName"
              allow-clear
            ></a-input>
          </a-form-item>
          <a-form-item label="类型" name="portType">
            <a-select
              ref="select"
              v-model:value="form.portType"
              @focus="focus"
              @change="handleChangePort"
              placeholder="请选择"
            >
              <a-select-option
                v-for="item in ports"
                :value="item.id"
                :key="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item label="位置" name="pictureType">
            <a-select
              ref="select"
              v-model:value="form.pictureType"
              :disabled="!form.portType"
              placeholder="请选择"
            >
              <a-select-option
                v-for="item in swiperTypes1"
                :value="item.id"
                :key="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-col :span="12">
            <a-form-item label="图片" name="pictureUrl">
              <a-upload
                v-model:file-list="pictureUrl"
                list-type="picture-card"
                class="avatar-uploader"
                :customRequest="uploadDetail_image"
                :disabled="modalTitle == '查看'"
              >
                <div v-if="pictureUrl.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
              文件大小不能超过100kb
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="跳转链接" name="jumpLink">
              <a-input
                placeholder="请输入跳转链接"
                allow-clear
                v-model:value="form.jumpLink"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="排序" name="sortId">
              <a-input
                placeholder="数字越大排序越靠前"
                v-model:value="form.sortId"
                allow-clear
              ></a-input>
            </a-form-item>
          </a-col>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>
<script>
import {
  reactive,
  ref,
  computed,
  createVNode,
  watch,
  toRefs,
  unref,
  toRaw,
  isReactive,
  toRef,
} from "vue";
import { ports, swiperType, swiperType1 } from "@/utils/dict.js";
import {
  CheckOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { uploadPicture } from "@/api/service/index.js";
import { Modal, message } from "ant-design-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import {
  selectAllConsumableBag,
  upOrDownConsumableBag,
  selectAllDetail,
  updateAndAddConsumableBag,
  deleteConsumableBag,
} from "@/api/consume/index.js";
import * as api from "@/api/content/swiper.js";
import { selectAllService, selectAllType } from "@/api/service/index.js";
import { deleteObjBlank } from "@/assets/js/common.js";
import { useModal } from "@/hooks"
export default {
  setup() {
    const searchRef = ref("");
    const formRef = ref("");

    const data = reactive({
      flag: false,
      list: [],
      loading: true,
      visible: false,
      detaiList: [],
      consumables: [], //默认绑定ID即可
      statusAct: 0,
      // 1护士端2用户端
      searchForm: {
        portType: 2,
      },
      typeList: [],
      form: {},
      value: [], //分类-这个远程加载的数据好像不可以哎
      defaultValue: [],
      ports,
      // data.searchForm.portType==0 ?
      swiperTypes: [...swiperType],
      swiperTypes1: [...swiperType1],

      serviceList: [{ name: "用户端" }, { name: "护士端" }],
      serviceColums: [
        {
          title: "类型",
          dataIndex: "name",
          className: "table",
          align: "center",
          slots: {
            customRender: "service",
          },
        },
      ],
      // 护士端，用户端
      serviceAct: 0,
      pictureUrl: [],
    });

    const title = ref(""); //分类名称

    const modalTitle = ref("新增");
    const rules = {
      pictureName: [{ required: true, message: "请输入!" }],
      portType: [{ required: true, message: "请选择!" }],
      pictureType: [{ required: true, message: "请选择!" }],
      // pictureUrl: [{ required: true, message: "请上传!",trigger: 'change' }],
      sortId: [
        { required: true, message: "请输入!" },
        {
          pattern: /^\+?[1-9][0-9]*$/,
          message: "请输入大于0的整数!",
        },
      ],
    };
    const rules1 = {
      name: [{ required: true, message: "请输入耗材名称!" }],
      sellPrice: [{ required: true, message: "请输入销售价!" }],
      serviceId: [{ required: true, message: "请输入服务类型!" }],
      typeId: [{ required: true, message: "请输入服务分类!" }],
      bazaarPrice: [{ required: true, message: "请输入市场价格!" }],
      bagNumber: [{ required: true, message: "请输入耗材编号!" }],
      // value: [{ required: true, message: "请选择耗材分类!" }],
    };

    // 分页器
    const page = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 0,
    });

    const saleStatusOptions = reactive([
      {
        name: "全部",
        id: "",
      },
      {
        name: "上架",
        id: 0,
      },
      {
        name: "下架",
        id: 1,
      },
    ]);
    const consumeOptions = reactive([
      {
        name: "耗材名称",
        id: 1,
      },
      {
        name: "耗材分类",
        id: 1,
      },
    ]);
    const delListId = ref([]); //删除数组ID集合
    const chooseStatus = (status, index) => {
      data.statusAct = index;
      data.searchForm.status = status;
      page.pageNum = 1;
      init();
    };
    // 查询
    const search = () => {
      page.pageNum = 1;
      init();
    };
    const columns = [
      {
        title: "图片",
        dataIndex: "pictureUrl",
        className: "table",
        slots: {
          customRender: "pictureUrl",
        },
      },
      {
        title: "标题",
        dataIndex: "pictureName",
        className: "table",
      },
      {
        title: "位置",
        dataIndex: "pictureType",
        className: "table",
        slots: {
          customRender: "pictureType",
        },
      },
      {
        title: "创建时间",
        dataIndex: "createdAt",
        className: "table",
      },

      {
        title: "操作",
        dataIndex: "operation",
        className: "table",
        slots: {
          customRender: "operation",
        },
      },
    ];

    // 分页器
    const pagination = computed(() => ({
      current: page.pageNum,
      pageSize: page.pageSize,
      pageSizeOptions: ["10", "20", "30"],
      showTotal: (total, range) => {
        return "共" + total + "条";
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true,
    }));

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, "当前分页");
      page.pageNum = pagination.current;
      page.pageSize = pagination.pageSize;

      // 请求列表接口
      init();
    };
    const cancel = () => {
      data.visible = false;
      title.value = "";
      data.form = {};
      data.consumables = [];
    };
    // 新增
    const add = () => {
      modalTitle.value = "新增";
      data.form = {};
      data.pictureUrl = [];
      data.visible = true;
    };
    const edit = async (item, name = "编辑") => {
      // item.typeId = String(item.typeId);
      // console.log(item, "item");
      data.form = item;
      data.swiperTypes1 =
        data.form.portType == 2 ? [...swiperType] : [...swiperType1];
      console.log(data.form);
      console.log(data.swiperTypes1);
      modalTitle.value = name;
      data.pictureUrl = [{ url: item.pictureUrl, status: "done" }];
      // data.consumables = item.consumables.map((el) => el.id);
      //
      // data.value[0] = String(item.typeId);
      data.visible = true;

      // 二级分类
      // let obj = item;
      // item.id = obj.typeId;
      // loadData([item]);
      // let obj = {
      //   pageNum: 1,
      //   pageSize: 80,
      //   typeId: item.typeId,
      // };
      // let res = await selectAllService(obj);
      // if (res.success) {
      //   let index = data.typeList.findIndex((el) => el.id == item.typeId);
      //   console.log(index, "查找到的index是-----");
      //   res.object.records.map((el) => (el.name = el.serveName));
      //   data.typeList[index].children = res.object.records;

      //   data.typeList = [...data.typeList];
      // }
      // data.value[1] = item.serviceId;

      // console.log(data.value, "默认选中的是");
    };
    const Typename = (id) => {
      let item = data.typeList.find((el) => el.id == id);
      console.log(item, "分类名字是");
      return item;
    };

    const serviceName = (id) => {
      let list = data.serviceList.find((el) => el.id == id);
      if (list.serviceName) {
        // return list.serveName;
        return list;
      }
    };
    const addSwiper = () => {
      formRef.value.validate().then(async () => {
        if (data.pictureUrl.length == 0) {
          message.error("请上传图片！");
          return;
        }
        // data.pictureUrl = data.pictureUrl[0].url;
        data.form.pictureUrl = data.pictureUrl[0].url;
        if (data.flag) return;
        data.flag = true;
        // data.form.pictureUrl = '1111';
        if (modalTitle.value == "新增") {
          api.addPicture({ ...data.form }).then((res) => {
            if (res.success) {
              data.flag = false;
              message.success("操作成功！");
              data.visible = false;
              page.pageNum = 1;
              init();
            }
          });
        } else {
          api.updatePicture(data.form).then((res) => {
            if (res.success) {
              data.flag = false;
              message.success("操作成功！");
              data.visible = false;
              page.pageNum = 1;
              init();
            }
          });
        }
      });
    };
    const save = () => {
      data.form.typeId = data.value[0];
      data.form.serviceId = data.value[1];
      console.log(data.form, "表单内容是");

      formRef.value.validate().then(async () => {
        let arr = [];
        // 查找耗材包明细内容两个数组比较
        data.detaiList.forEach((el) => {
          data.consumables.forEach((item) => {
            if (item == el.id) {
              arr.push(el);
            }
          });
        });
        if (data.value.length == 0) {
          message.error("请选择耗材分类!!!");
          return;
        }

        data.form.consumables = arr;
        let res = await updateAndAddConsumableBag(data.form);
        if (res.success) {
          message.success("新增成功");
          data.visible = false;
        }
      });
    };
    const closeModal = (e) => {
      data[e] = false;
      if (e == "itemVisible") {
        data.itemForm = {};
      }
      if (e == "visible") {
        data.form = {};
        data.pictureUrl = [];
      }
    };
    // 删除
    const del = (key) => {
      const {closeModal} = useModal.confirm({
        title: () => "你确定删除当前项吗?",
        icon: () => createVNode(QuestionCircleOutlined),
        content: () =>
          createVNode(
            "div",
            {
              style: "color:red;",
            },
            "删除当前数据后不可恢复，请谨慎考虑。"
          ),
        onOk: async () => {
          let res = await api.deletePictureById({ pictureId: Number(key) });
          if (res.success) {
            message.success("删除成功");
            init();
            closeModal()

          }
        },
        class: "test",
      });
    };
    const selectConsume = (e) => {
      console.log(e);
    };
    const selectService = (e) => {
      // console.log(e, "服务类型");s
    };
    const selectType = (e) => {};
    // 上传头图
    const uploadDetail_image = (file) => {
      uploadImage(file, "pictureUrl");
    };
    // 公共的上传图片
    const uploadImage = async (file, e) => {
      let formData = new FormData();
      formData.append("file", file.file);
      let res = await uploadPicture(formData, "ali");
      // // url存入列表中,为什么是两个fileList
      data[e] = data[e].filter((el) => el.status == "done");
      if (res.success) {
        data[e].push({
          uid: file.file.uid,
          url: res.object,
          status: "done",
          name: file.file.name,
        });
      }
      console.log(data[e], "data[e]是--");
    };
    // 全选反选
    const rowSelection = ref({
      checkStrictly: false,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(
          `selectedRowKeys: ${selectedRowKeys}`,
          "selectedRows: ",
          selectedRows
        );
        delListId.value = selectedRowKeys;
      },
      onSelect: (record, selected, selectedRows) => {
        //console.log(record, selected, selectedRows,'选择多项');
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        //console.log(selected, selectedRows, changeRows,'全选操作');
        // 数组项
      },
    });
    // 删除多项
    const listDel = () => {
      const {closeModal} = useModal.confirm({
        title: "确定删除所选内容项吗?",
        icon: createVNode(ExclamationCircleOutlined),
        content: "删除后将不可恢复，请谨慎操作。",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk: async () => {
          console.log(delListId.value);
          let data = delListId.value.map((el) => (el = Number(el)));

          let res = await deleteConsumableBag(data);
          if (res.success) {
            message.success("删除成功");
            init();
            closeModal()
          }
        },
        
      });
    };

    // 是否上下架 就把原来的状态改变下就行，传递下当前项的耗材ID即可，
    const changeStack = (checked, index, id) => {
      console.log(page.pageNum);
      console.log(checked, index, "是否上下架");
      let title = checked == 0 ? "上架" : "下架";
      // 弹框提示？确定上下架吗
      const {closeModal} = useModal.confirm({
        title: () => `确定${title}当前耗材包吗?`,
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: async () => {
          let res = await upOrDownConsumableBag(id);
          if (res.success) {
            data.list[index].status = Number(checked);
            closeModal()

          }
        },
        onCancel() {
          let flag = checked == 0 ? 1 : 0;
          data.list[index].status = flag;
          closeModal()
        },
        class: "test",
      });
    };
    // initServiceList();

    init();
    // initAllDetailList();
    async function init() {
      let obj = {
        pageNum: page.pageNum,
        pageSize: page.pageSize,
        ...data.searchForm,
      };
      let res = await api.list(obj);
      if (res.success) {
        let {
          object: { object },
        } = res;
        object.records.map((el) => (el.key = el.id));
        data.list = object.records;
        data.loading = false;
        page.total = object.total;
      }
    }
    // 一级分类
    // async function initServiceList() {
    //   let obj = {
    //     pageNum: 1,
    //     pageSize: 80,
    //   };
    //   let res1 = await selectAllType(obj);
    //   if (res1.success) {
    //     res1.object.records.map((el) => (el.isLeaf = false)); //id是string类型的
    //     data.typeList = res1.object.records;
    //   }
    // }
    // async function initAllDetailList() {
    //   let res = await selectAllDetail();
    //   if (res.success) {
    //     data.detaiList = res.object;
    //   }
    // }

    const loadData = async (selectedOptions) => {
      console.log("点击了选择", selectedOptions);
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true; // load options lazily

      let obj = {
        pageNum: 1,
        pageSize: 80,
        typeId: selectedOptions[0].id,
      };
      let res = await selectAllService(obj);
      if (res.success) {
        targetOption.loading = false;
        res.object.records.map((el) => (el.name = el.serveName));
        targetOption.children = res.object.records;

        data.typeList = [...data.typeList];
      }
    };
    const getChildrenList = (record, index) => {
      data.serviceAct = index;
      data.searchForm = {};

      // portType:0所有/1护士/2用户
      //  index==1 表示父级为护士端
      data.searchForm.portType = index == 1 ? 1 : 2;
      // debugger;
      (data.swiperTypes = index == 1 ? [...swiperType1] : [...swiperType]),
        init();
    };
    const handleChangePort = () => {
      data.swiperTypes1 =
        data.form.portType == 2 ? [...swiperType] : [...swiperType1];
      data.form.pictureType = "";
    };
    const handleReset = () => {
      data.searchForm = {};
      page.pageNum = 1;
      init();
    };

    const methods = {};
    return {
      ...methods,
      ...toRefs(data),
      saleStatusOptions,
      consumeOptions,
      searchRef,
      modalTitle,
      formRef,
      rules,
      rules1,
      columns,
      pagination,
      title,
      labelCol: { style: { width: "150px" } },
      wrapperCol: { span: 14 },
      handleTableChange,
      search,
      add,
      del,
      save,
      cancel,
      edit,
      rowSelection,
      listDel,
      changeStack,
      serviceName,
      selectConsume,
      selectService,
      chooseStatus,
      Typename,
      selectType,
      loadData,
      uploadDetail_image,
      closeModal,
      getChildrenList,
      addSwiper,
      handleChangePort,
      handleReset,
    };
  },

  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    QuestionCircleOutlined,
    PlusOutlined,
  },
};
</script>

<style scoped lang="less">
.act {
  color: #2a9d8f;
}
.name-act {
  color: #2a9d8f;
  font-weight: bolder;
}
</style>
